package com.boarsoft.dao.sharding.group;

import java.util.Map;

import javax.sql.DataSource;

import com.boarsoft.dao.sharding.bean.HashedEntity;

public class SimpleHashShardGroup implements ShardGroup {
	/** */
	protected String prefix = "";
	/** */
	protected Map<String, DataSource> dataSourceMap;

	@Override
	public DataSource getDataSource() {
		return dataSourceMap.get(prefix.concat("0"));
	}

	@Override
	public DataSource getDataSource(Object key) {
		// TODO 增强健壮性，HAHS环实现
		int s = dataSourceMap.size();
		int h = 0;
		if (s > 1 && key != null) {
			if (key instanceof HashedEntity) {
				h = ((HashedEntity) key).hash();
			} else {
				h = key.hashCode();
			}
			h = Math.abs(h) % s;
		}
		String k = new StringBuilder(prefix).append(h).toString();
		return dataSourceMap.get(k);
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public Map<String, DataSource> getDataSourceMap() {
		return dataSourceMap;
	}

	public void setDataSourceMap(Map<String, DataSource> dataSourceMap) {
		this.dataSourceMap = dataSourceMap;
	}
}